//
//  PublishActionViewController.m
//  com.modada.new
//
//  Created by ferver7 on 2019/5/11.
//  Copyright © 2019 ferver7. All rights reserved.
//

#import "PublishActionViewController.h"
#import "PostImageCell.h"
#import "ImagePostTool.h"
#import "PublishKindsSelViewController.h"

@interface PublishActionViewController ()
@property (weak, nonatomic) IBOutlet PPTextfield *priceTf;
@property (weak, nonatomic) IBOutlet PlaceholderTextView *expTV;
@property (weak, nonatomic) IBOutlet UILabel *kindLabel;
@property (weak, nonatomic) IBOutlet PostImageCell *postImageModule;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (nonatomic,strong) AxcUI_ActivityHUD * axcUI_ActivityHUD;
@property (nonatomic,strong) NSMutableArray * postImgsURL;//上传的图片
@property (nonatomic,assign) CGFloat postCellHeight;
@property (nonatomic,strong) NSString *selKindName;
@property (nonatomic,strong) NSString *selKindID;
@property (nonatomic,assign) NSInteger selKindIndex;
@end

@implementation PublishActionViewController
-(void)rightAction:(UIButton *)sender
{
    if(self.priceTf.text.length <1){
        [AxcUI_Toast AxcUI_showCenterWithText:@"请输入价格"];
        return;
    }
    if(self.expTV.text.length < 1){
        [AxcUI_Toast AxcUI_showCenterWithText:@"请输入商品描述"];
        return;
    }
    if (!self.selKindID) {
        [AxcUI_Toast AxcUI_showCenterWithText:@"请选择商品分类"];
        return;
    }
    if (self.postImgsURL.count == 0) {
        [AxcUI_Toast AxcUI_showCenterWithText:@"至少上传一张商品图片"];
        return;
    }
    NSMutableDictionary * requestInfo = [[NSMutableDictionary alloc]init];
    setDickeyobj(requestInfo, [AppUserBaseModel sharedUserData].detailedAddress, @"address");
    setDickeyobj(requestInfo, [AppUserBaseModel sharedUserData].county, @"area");
    setDickeyobj(requestInfo, [AppUserBaseModel sharedUserData].city, @"city");
    setDickeyobj(requestInfo, [AppUserBaseModel sharedUserData].province, @"province");
    setDickeyobj(requestInfo, [AppUserBaseModel sharedUserData].uid, @"uid");
    setDickeyobj(requestInfo, @"标题隐藏", @"title");
    setDickeyobj(requestInfo, self.priceTf.text, @"price");
    setDickeyobj(requestInfo, self.expTV.text, @"content");
    NSString* images ;
    for (NSString * imageUrl in self.postImgsURL) {
        if (images.length == 0) {
            images = imageUrl;
        }else{
            images = [NSString stringWithFormat:@"%@,%@",images,imageUrl];
        }
    }
    setDickeyobj(requestInfo, images, @"image");
    setDickeyobj(requestInfo, self.selKindID, @"btId");
    [PPNetworkHelper POST:app_circle_release parameters:requestInfo success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [AxcUI_Toast AxcUI_showCenterWithText:responseObject[@"msg"]];
        }
    } failure:^(NSError *error) {
        
    } showLoading:self.view];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    mNavitationTitle(@"发布");
    self.priceTf.maxTextLength = 10;
    self.priceTf.isOnlyNumber = YES;
    
    self.expTV.placeholderLabel.font = [UIFont systemFontOfSize:14];
    self.expTV.placeholder = @"请填写商品描述...";
    self.expTV.placeholderLabel.textAlignment = NSTextAlignmentLeft;
    self.expTV.placeholderFrame = CGRectMake(5, 5, mScreenWidth-40, 20);
    self.expTV.placeholderLabel.textColor = [UIColor AxcUI_colorWithHexCode:@"#B4B4B4"];
    self.expTV.font = [UIFont systemFontOfSize:14];
    self.expTV.maxLength = 200;
    self.expTV.wordNumLabel.hidden = NO;
    self.expTV.showsVerticalScrollIndicator = NO;
    
    self.postImgsURL = [[NSMutableArray alloc]init];
    self.postImageModule.contentMargin = 0;
    self.postImageModule.contentPadding = 15;
    self.postImageModule.itemSpace = 5;
    self.postImageModule.rootVC = self;
    self.postCellHeight = (mScreenWidth-70)/3+20;
    self.postImageModule.maxSelImages = 6;
    self.postImageModule.rootVC = self;
    //3、随时获取新的布局高度
    WS(weakSelf);
    [self.postImageModule observeViewHeight:^(CGFloat value) {
        weakSelf.postCellHeight = value;
        [weakSelf.tableView reloadData];
    }];
    [self.postImageModule observeSelectedMediaArray:^(NSMutableArray<ACMediaModel *> *list) {
        [self updateImages:list];
    }];
    [self.postImageModule observePostExchangeImagesPoszition:^(NSInteger start, NSInteger end) {
        NSDictionary * infoDic = self.postImgsURL[start];
        [self.postImgsURL removeObject:infoDic];
        [self.postImgsURL insertObject:infoDic atIndex:end];
    }];
    [self.postImageModule observeImageDelBlock:^(NSInteger index) {
        [self.postImgsURL removeObjectAtIndex:index];
    }];
    self.addressLabel.text = [NSString stringWithFormat:@"%@%@%@",[AppUserBaseModel sharedUserData].city,[AppUserBaseModel sharedUserData].county,[AppUserBaseModel sharedUserData].detailedAddress];
    [self addRightBarButtonItemWithTitle:@"发布" action:@selector(rightAction:)];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 4 ) {
        return self.postCellHeight+10;
    }
    if (indexPath.row ==2 ) {
        return 150;
    }
    return 50;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        PublishKindsSelViewController * kVc = mGetStoryboardViewController(@"Main", @"publishKindsSelViewController");
        kVc.returnBtIdBlock = ^(NSString * _Nonnull name, NSString * _Nonnull btid,NSInteger selIndex) {
            self.selKindName = name;
            self.selKindID = btid;
            self.selKindIndex = selIndex;
            self.kindLabel.text = name;
        };
        if (self.selKindName) {
            kVc.tagSelYES = YES;
            kVc.tagSel = self.selKindIndex;
        }
        [self.navigationController pushViewController:kVc animated:YES];
    }
}
#pragma mark -
#pragma mark - **************** 上传图片
-(void)updateImages:(NSArray *)list
{
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 1;
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新，
        [self.axcUI_ActivityHUD AxcUI_showWithText:[NSString stringWithFormat:@"正在上传第%ld张图片",self.postImgsURL.count+1] shimmering:YES];
    });
    
    for (int i=0;i<list.count;i++) {
        ACMediaModel * model  = list[i];
        [queue addOperationWithBlock:^{
            NSLog(@"第一个任务");
            //延迟调用
            ImagePostTool * imgesPostTool = [[ImagePostTool alloc]init];
            id obj = [imgesPostTool UpLoadingForInfo:@[@{@"file":UIImageJPEGRepresentation(model.image, 1.0f)}]];
            if ([obj isKindOfClass:[NSDictionary class]]) {
                NSArray * info = obj[@"data"];
//
//                [info setObject:info[@"path"] forKey:@"url"];
//                [info removeObjectForKey:@"path"];
                
                [self.postImgsURL addObjectVerify:info.firstObject];
            }else{
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                [self.axcUI_ActivityHUD AxcUI_updateText:[NSString stringWithFormat:@"正在上传第%ld张图片",self.postImgsURL.count+1] shimmering:NO];
            });
            //取消延迟调用  用来处理一直上传失败
            //            NSLog(@"%@",info);
            if (i == list.count-1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //回调或者说是通知主线程刷新，
                    [self.axcUI_ActivityHUD AxcUI_dismiss];
                    [self.postImageModule.postImageArr addObjectsFromArray:list];
                });
            }
            
        }];
    }
}

-(AxcUI_ActivityHUD *)axcUI_ActivityHUD
{
    if (!_axcUI_ActivityHUD) {
        _axcUI_ActivityHUD = [[AxcUI_ActivityHUD alloc] init];
        _axcUI_ActivityHUD.axcUI_isTheOnlyActiveView = NO;  // 能否点击背景
        _axcUI_ActivityHUD.axcUI_appearAnimationType = AxcActivityHUDAppearAnimationTypeFadeIn;       // 入场风格
        _axcUI_ActivityHUD.axcUI_disappearAnimationType = AxcActivityHUDDisappearAnimationTypeFadeOut; // 出场风格
        _axcUI_ActivityHUD.axcUI_overlayType = AxcActivityHUDOverlayTypeTransparent;    //  背景框的风格
    }
    return _axcUI_ActivityHUD;
}
@end
